package com.cloud.shopping.tool;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @author John.zhang
 * @version Id: UrlUtils, v 1.0 2021/1/2 15:32 ZhiYong Exp $
 * URL工具
 */
public class UrlUtils {

    /**
     * 去掉URL中指定的参数
     */
    public static String replaceUrlParameter(String url, String... names) {
        for (String name : names) {
            url = url.replaceAll("(&" + name + "=([0-9\\w]+))|(" + name + "=([0-9\\w]+)&)|(" + name + "=([0-9\\w]+))", "");
        }
        return url;
    }

    /***
     * 当前请求地址组装
     */
    public static String map2url(String baseUrl, Map<String, Object> searchMap, String... names) {
        //参数获取
        String param = map2param(searchMap);
        if (!StringUtils.isEmpty(param)) {
            baseUrl += "?" + param;
        }
        //去掉指定参数
        baseUrl = replaceUrlParameter(baseUrl, names);
        return baseUrl;
    }

    /**
     * 将map转换成url参数
     *
     * @param map map
     * @return String
     */
    public static String map2param(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue());
            sb.append("&");
        }
        String parameters = sb.toString();
        String chart = "&";
        if (parameters.endsWith(chart)) {
            parameters = StringUtils.substringBeforeLast(parameters, "&");
        }
        return parameters;
    }

}
